import os
import numpy as np
import winsound
import time
import matplotlib.pyplot as plt



def get_data(file_path, start=XXX, stop=XXX, div=XXX):
    with open(file_path, 'r', encoding='gbk') as f:
        data_all = f.readlines()[::-1]
        data = []
        for i in data_all:
            if '>>>>>Begin Spectral Data<<<<<' in i:
                break
            i = i.replace("\n", "")
            data.append(i.split("\t"))
        data = data[::-1]
    x = [float(i[0]) for i in data[start:stop]]
    y = [float(i[1]) for i in data[start:stop]]
    x1 = []
    m = x[0]
    while m <= x[-1]:
        x1.append(m)
        m += div
    return [x, x1, y]


def data_fitting(data, power=60, error=1, div=0.001, count=4):
    x1 = np.array(data[0])
    x2 = np.array(data[1])
    y = np.array(data[2])
    an = np.polyfit(x1, y, power)
    result = np.polyval(an, x2)
    y_max = np.max(result)
    h = float(y_max) / 2
    index = list(np.where(result == y_max))[0][0]
    x_max = float(x2[index])
    flag = True
    result1 = result[:index]
    result2 = result[index:]
    temp = error
    while flag:
        index1 = np.where((result1 >= h - temp) & (result1 <= h + temp))
        if len(list(index1)[0]) != 1:
            temp -= div
        else:
            flag = False
            pp1 = float(x2[list(index1)[0]])
    flag = True
    temp = error
    while flag:
        index1 = np.where((result2 >= h - temp) & (result2 <= h + temp))
        if len(list(index1)[0]) != 1:
            temp -= div
        else:
            flag = False
            pp2 = float(x2[list(index1 + index)[0]])
    return [round(x_max, count), round(y_max, count), round((pp1 + pp2) / 2, count)]

last_data = []
t = 3
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
ax.set(xlabel='PP', ylabel='PPC', zlabel='PI')
ax.set_xlim3d(xmin=XXX, xmax=XXX)
ax.set_ylim3d(ymin=XXX, ymax=XXX)
ax.set_zlim3d(zmin=XXXXX, zmax=XXXXX)
while True:
    try:
        a = os.listdir('data')
        time.sleep(t)
    except:
        time.sleep(t)
        a = os.listdir('data')
        time.sleep(t)
    for i in a:
        if i not in last_data:
            last_data.append(i)
            print(i)
            point = get_data('data//' + i)
            result = data_fitting(point)
            if XXX <= result[0] <= XXX and XXXXX <= result[1] <= XXXXX and XXXXX <= result[2] <= XXXXX:
                print(i + ':' + str(result))
                ax.scatter(result[0], result[2], result[1], c='#ee0b0b', marker='*')
                winsound.PlaySound('sound.wav', flags=1)
                with open('Switch.txt', 'w', encoding='utf-8') as f:
                    f.write('1')
            else:
                with open('Switch.txt', 'r', encoding='utf-8') as f:
                    play = int(f.read())
                if play == 1:
                    winsound.PlaySound('sound.wav', flags=1)
                ax.scatter(result[0], result[2], result[1])
            plt.pause(2)
